/* eslint-disable array-callback-return */

import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Spin, Select, Steps, Input, Divider, DatePicker, Switch } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;
const { Description } = DescriptionList;

@connect(({ adjustinfo, loading, publicdata }) => ({
  loading: loading.models.adjustinfo,
  adjustinfo,
  dictCode: publicdata.dictCode,
  // adjusttask,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //  isSwitch: false,
      //  isCostCenter: false,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const query = queryString.parse(location.search);
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE', 'PAY_FEES_WAY'],
    }).then(() => {
      // 获取报价单信息
      dispatch({
        type: 'adjustinfo/fetchAdjCharInfoDetail',
        payload: query,
      });
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const resetAdjustInfo = {
      updateBaseInfo: {},
      updateCostGenter: {},
      updatePdAmo: [],
      costCenterData: [],
    };
    dispatch({
      type: 'adjustinfor/updateModelData',
      payload: { ...resetAdjustInfo },
    });
  }

  // switch按钮开关控制
  changeSwitch = checked => {
    this.setState({
      isSwitch: checked,
    });
  };

  costOnChange = checked => {
    this.setState({
      costFlag: checked,
    });
  };

  quoteOnChange = (item, checked, id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'adjustinfo/changeQute',
      payload: { checked, id },
    });
  };

  // 提交数据
  submit = () => {
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      const { adjustinfo } = this.props;
      const { sendId } = adjustinfo.updateBaseInfo;
      const temp = values;
      adjustinfo.updatePdAmo.map((c, i) => {
        if (c.serAmoFlag) {
          temp.updatePdAmo[i].pdId = c.pdId;
          temp.updatePdAmo[i].packNo = c.packNo;
        }
      });
      if (values.costFlag) {
        temp.updateCostGenter = {
          costCenter: values.costCenter,
        };
        delete temp.costCenter;
      }
      if (values.entryDate) {
        temp.entryDate = values.entryDate.format('YYYY-MM-DD');
      }
      // console.log('valusd', values, JSON.stringify(values));
      if (!err) {
        const { dispatch } = this.props;
        dispatch({
          type: 'adjustinfo/submit',
          payload: { ...values, sendId },
        });
      }
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      adjustinfo: { updateBaseInfo, updateCostGenter, updatePdAmo, costCenterData },
    } = this.props;
    const { isSwitch, costFlag } = this.state;
    // 判断有无修改
    const isEditInfo = () => {
      let isEdit = false;
      const amoSwitch = updatePdAmo.some(item => item.serAmoFlag);
      const switchValueList = [isSwitch, costFlag, amoSwitch];
      isEdit = switchValueList.some(item => item);
      return isEdit;
    };
    return (
      <Form layout="inline">
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              <Steps current={1} style={{ marginBottom: 70 }}>
                <Step title="选择调整项" />
                <Step title="填写修改信息" />
                <Step title="完成" />
              </Steps>
              <Card
                title={
                  <div style={{ position: 'relative' }}>
                    <span style={{ fontWeight: 'bolder' }}>基本信息</span>
                    <FormItem colon={false} style={{ position: 'absolute', left: 90, top: '-5px' }}>
                      {getFieldDecorator('baseInfoFlag', {
                        valuePropName: 'checked',
                        rules: [{ required: false, message: '请选择' }],
                        initialValue: false,
                      })(
                        <Switch
                          checkedChildren="修改"
                          unCheckedChildren="不修改"
                          style={{ width: 80 }}
                          onChange={check => this.changeSwitch(check, 'baseInfoFlag')}
                          disabled={!(updateBaseInfo && updateBaseInfo.adjFlag)}
                        />
                      )}
                    </FormItem>
                  </div>
                }
              >
                <DescriptionList>
                  <Description term="客户名称">
                    {updateBaseInfo && updateBaseInfo.custName ? updateBaseInfo.custName : '--'}
                  </Description>

                  <Description term="商务合同">
                    {updateBaseInfo && updateBaseInfo.custContName
                      ? updateBaseInfo.custContName
                      : '--'}
                  </Description>

                  <Description term="报价单">
                    {updateBaseInfo && updateBaseInfo.quoName ? updateBaseInfo.quoName : '--'}
                  </Description>
                  <Description term="姓名">
                    {updateBaseInfo && updateBaseInfo.empName ? updateBaseInfo.empName : '--'}
                  </Description>
                  <Description term="证件类型">
                    {updateBaseInfo && updateBaseInfo.idTypeName ? updateBaseInfo.idTypeName : '--'}
                  </Description>
                  <Description term="证件号">
                    {updateBaseInfo && updateBaseInfo.idCode ? updateBaseInfo.idCode : '--'}
                  </Description>
                  <Description term="国籍">
                    {updateBaseInfo && updateBaseInfo.nationName ? updateBaseInfo.nationName : '--'}
                  </Description>

                  <Description term="出生日期">
                    {updateBaseInfo && updateBaseInfo.birthDate
                      ? moment(updateBaseInfo.birthDate).format('YYYY-MM-DD')
                      : '--'}
                  </Description>
                  <Description term="性别">
                    {updateBaseInfo && updateBaseInfo.genderName ? updateBaseInfo.genderName : '--'}
                  </Description>

                  {isSwitch ? (
                    <FormItem
                      label="电话"
                      style={{ margin: '-10px 0 7px 16px', width: '33%' }}
                      className={styles.adjustInfo}
                    >
                      {getFieldDecorator('mobile', {
                        // valuePropName: 'checked',
                        rules: [
                          {
                            required: false,
                            message: '请输入11位手机号码',
                            pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                          },
                        ],
                        initialValue: updateBaseInfo.mobile ? updateBaseInfo.mobile : undefined,
                      })(<Input />)}
                    </FormItem>
                  ) : (
                    <Description term="电话">
                      {updateBaseInfo && updateBaseInfo.mobile ? updateBaseInfo.mobile : null}
                    </Description>
                  )}
                  {isSwitch ? (
                    <FormItem
                      label="员工邮箱"
                      style={{ margin: '-10px 0 0 4px', width: '31%' }}
                      className={styles.adjustInfo}
                    >
                      {getFieldDecorator('email', {
                        //  valuePropName: 'checked',
                        rules: [{ required: false, type: 'email', message: '请输入邮箱格式!' }],
                        initialValue: updateBaseInfo.email ? updateBaseInfo.email : undefined,
                      })(<Input />)}
                    </FormItem>
                  ) : (
                    <Description term="员工邮箱">
                      {updateBaseInfo && updateBaseInfo.email ? updateBaseInfo.email : '--'}
                    </Description>
                  )}
                  {isSwitch ? (
                    <FormItem
                      label="入职日期"
                      style={{ margin: '-10px 0 0 30px', width: '30%' }}
                      className={styles.adjustInfo}
                    >
                      {getFieldDecorator('entryDate', {
                        //  valuePropName: 'entryDate',
                        rules: [{ required: false, message: '请输入' }],
                        initialValue: updateBaseInfo.entryDate
                          ? moment(
                              moment(updateBaseInfo.entryDate).format('YYYYMMDD'),
                              'YYYY-MM-DD'
                            )
                          : null,
                      })(
                        <DatePicker placeholder="请选择" allowClear={false} format="YYYY-MM-DD" />
                      )}
                    </FormItem>
                  ) : (
                    <Description term="入职日期">
                      {updateBaseInfo && updateBaseInfo.entryDate
                        ? moment(updateBaseInfo.entryDate).format('YYYY-MM-DD')
                        : '--'}
                    </Description>
                  )}
                </DescriptionList>
              </Card>

              <Card
                title={
                  <div style={{ position: 'relative' }}>
                    <span style={{ fontWeight: 'bolder' }}>成本中心</span>
                    <FormItem colon={false} style={{ position: 'absolute', left: 90, top: '-5px' }}>
                      {getFieldDecorator('costFlag', {
                        valuePropName: 'checked',
                        rules: [{ required: false, message: '请选择' }],
                        initialValue: false,
                      })(
                        <Switch
                          checkedChildren="修改"
                          unCheckedChildren="不修改"
                          style={{ width: 80 }}
                          onChange={check => this.costOnChange(check, 'costcenter')}
                          disabled={!(updateCostGenter && updateCostGenter.adjFlag)}
                        />
                      )}
                    </FormItem>
                  </div>
                }
              >
                <FormItem label="成本中心" className={styles.adjustInfo}>
                  {costFlag ? (
                    <div>
                      {getFieldDecorator('costCenter', {
                        // valuePropName: 'checked',
                        rules: [{ required: false, message: '请输入' }],
                        initialValue: updateCostGenter.costCenter
                          ? `${updateCostGenter.costCenter}`
                          : undefined,
                      })(
                        <HOCSelect placeholder="请选择" style={{ width: 200 }}>
                          {costCenterData.map(item => (
                            <Option key={item.costCenterId}>{item.name}</Option>
                          ))}
                        </HOCSelect>
                      )}
                      <span
                        style={{
                          fontSize: '12px',
                          color: '#ccc',
                          marginLeft: 20,
                        }}
                      >
                        说明：修改之后当月生效，只有已生成的待收费账单变化。新生成的账单会按照最新规则生成。
                      </span>
                    </div>
                  ) : (
                    <span>
                      {updateCostGenter && updateCostGenter.costCenterName
                        ? updateCostGenter.costCenterName
                        : '--'}
                    </span>
                  )}
                </FormItem>
              </Card>
              <Card
                title={
                  <div style={{ position: 'relative' }}>
                    <span style={{ fontWeight: 'bolder' }}>服务费</span>
                    <span
                      //    colon={false}
                      style={{
                        position: 'absolute',
                        top: 2,
                        left: 60,
                        fontSize: '12px',
                        color: '#ccc',
                      }}
                    >
                      （临时修改本月的服务费）
                    </span>
                  </div>
                }
              >
                {updatePdAmo.map((item, i) => (
                  <Card style={{ marginBottom: 10 }}>
                    {item.updatePdPackInfoList.map(c => (
                      <DescriptionList style={{ marginBottom: 8 }}>
                        <Description term="产品名称">{c.pdName ? c.pdName : '--'}</Description>
                        <Description term="缴费方式">
                          {c.payWayName ? c.payWayName : '--'}
                        </Description>
                        <Description term="缴费险种">{c.assName ? c.assName : '--'}</Description>
                      </DescriptionList>
                    ))}
                    <Divider dashed="true" />
                    <DescriptionList style={{ marginBottom: 26 }}>
                      <Description>
                        <FormItem label="报价金额" className={styles.adjustInfo}>
                          {item.serAmoFlag ? (
                            getFieldDecorator(`updatePdAmo[${i}][serAmo]`, {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入小数点不超过2位的数字',
                                  pattern: /^-?\d+\.?\d{0,2}$/,
                                },
                              ],
                              initialValue: item.quoAmo ? item.quoAmo : undefined,
                            })(<Input style={{ width: 80 }} />)
                          ) : (
                            <span>{item.quoAmo ? item.quoAmo.toFixed(2) : '--'}</span>
                          )}

                          {getFieldDecorator(`updatePdAmo[${i}][serAmoFlag]`, {
                            valuePropName: 'checked',
                            rules: [{ required: false, message: '请选择' }],
                            initialValue: false,
                          })(
                            <Switch
                              checkedChildren="修改"
                              unCheckedChildren="不修改"
                              style={{ width: 80, marginLeft: 10, marginTop: '-3px' }}
                              onChange={check => this.quoteOnChange(item, check, i)}
                            />
                          )}
                        </FormItem>
                      </Description>
                      <Description term="税金">
                        {item.taxAmo || item.taxAmo === 0 ? item.taxAmo : '--'}
                        <span style={{ marginLeft: 18 }}>
                          ( 税率：
                          {item.taxRate || item.taxRate === 0 ? item.taxRate : '-- '})
                        </span>
                      </Description>
                    </DescriptionList>
                  </Card>
                ))}
              </Card>
              <div style={{ marginTop: '100px', marginBottom: '30px', textAlign: 'center' }}>
                <Button style={{ marginRight: '30px' }} onClick={() => router.goBack()}>
                  返回
                </Button>
                <Button type="primary" onClick={this.submit} disabled={!isEditInfo()}>
                  提交
                </Button>
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
